package com.example.opengldemo._11_;

import android.opengl.GLES30;
import android.util.Log;
import android.view.View;

import com.example.opengldemo.util.ShaderBuffer;
import com.example.opengldemo.util.ShaderHandle;
import com.example.opengldemo.util.ShaderUtil;

public class TextureGraphics {
    public ShaderHandle shaderHandle;
    public ShaderBuffer shaderBuffer;

    float[] vertexArray = new float[]{
            -2f , 2f , 0f ,
            -2f , -2f , 0 ,
            2f , 2f , 0 ,
            2f , 2f , 0 ,
            -2f , -2f , 0 ,
            2f , -2f , 0
    };


    float[] texcoorsArray = new float[]{
            0 ,0 ,
            0, 1f ,
            1f, 0 ,
            1f, 0 ,
            0, 1f ,
            1f ,1f
    };


    public TextureGraphics(View view) {
        initShaderHandle(view);
        initShaderBuffer();
    }

    private void initShaderBuffer() {
        shaderBuffer = new ShaderBuffer();
        shaderBuffer.vCount = vertexArray.length / 3;
        shaderBuffer.setVertexBuffer(vertexArray);
        shaderBuffer.setTexcoorBuffer(texcoorsArray);
    }

    private void initShaderHandle(View view) {
        String vertexSrc = ShaderUtil.loadFromAssetsFile("mixing/vertex.sh", view.getResources());
        String fragSrc = ShaderUtil.loadFromAssetsFile("mixing/fragment.sh", view.getResources());
        shaderHandle = new ShaderHandle(ShaderUtil.createProgram(vertexSrc, fragSrc));
    }

    public void drawSelf(int texture) {

        GLES30.glUseProgram(shaderHandle.getProgram());

        GLES30.glVertexAttribPointer(
                shaderHandle.get_A_PositionHandle(),
                3,
                GLES30.GL_FLOAT,
                false,
                3 * 4,
                shaderBuffer.getVertexBuffer()
        );
        GLES30.glVertexAttribPointer(
                shaderHandle.get_A_TexCoorsHandle(),
                2,
                GLES30.GL_FLOAT,
                false,
                2 * 4,
                shaderBuffer.getTexcoorBuffer()
        );

        GLES30.glUniformMatrix4fv(
                shaderHandle.get_U_MVPMatrixHandle(),
                1,
                false,
                shaderBuffer.getMVPMatrixArray(),
                0
        );

        GLES30.glActiveTexture(GLES30.GL_TEXTURE0);
        GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, texture);

        GLES30.glEnableVertexAttribArray(shaderHandle.get_A_PositionHandle());
        GLES30.glEnableVertexAttribArray(shaderHandle.get_A_TexCoorsHandle());

        GLES30.glDrawArrays(GLES30.GL_TRIANGLES, 0, shaderBuffer.vCount);

        GLES30.glDisableVertexAttribArray(shaderHandle.get_A_PositionHandle());
        GLES30.glDisableVertexAttribArray(shaderHandle.get_A_TexCoorsHandle());


    }
}
